#include "my_Udp_cilent.hpp"
#include<pthread.h>

void* recv(void*arg)
{
    int sock=*(static_cast<int *>(arg));
    struct sockaddr_in tmp;

    while(1)
    {
        socklen_t len = sizeof(tmp);
        char buf[1024];

        int ret=recvfrom(sock, buf, sizeof(buf) - 1, 0, (sockaddr *)(&tmp), &len);
        if (ret < 0)
        {
            cerr << "客户端接收失败：" << strerror(errno) << endl;
            exit(RECV_ERR);
        }
        buf[ret] = '\0';
        cout << buf << endl;
    }

}

int main(int arg, char *args[])
{
    string stringIp = args[1];
    string stringPort = args[2];
    // cout<<"你好！我是客户端！\n";
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        cerr << "客户端创建套接字失败：" << strerror(errno) << endl;
        exit(SOCK_ERR);
    }
    struct sockaddr_in peer;
    bzero(&peer, sizeof(peer));
    peer.sin_addr.s_addr = inet_addr(stringIp.c_str());
    peer.sin_family = AF_INET;
    peer.sin_port = htons(atoi(stringPort.c_str()));
    pthread_t tid;
    pthread_create(&tid,NULL,recv,&sock);
    while (1)
    {
        string cilent_buf;
        char buf[1024];
        //cin >> cilent_buf;
        getline(cin,cilent_buf);

        if (sendto(sock, cilent_buf.c_str(), cilent_buf.size(), 0, (sockaddr *)(&peer), sizeof(peer)) < 0)
        {
            cerr << "客户端发送失败 " << strerror(errno) << endl;
            // cout << "测试：" << cilent_buf << endl;
            exit(SENDTO_ERR);
        }
        
    }
    return 0;
}